from flask import g, abort
from flask_login import current_user
from wtforms import Form, StringField, IntegerField, FloatField
from wtforms.validators import DataRequired, Length, NumberRange, ValidationError

from app.model.order import Order, OrderStatus
from app.model.product import Product


class NewOrderForm(Form):
    product_id = StringField(validators=[DataRequired()])
    count = IntegerField(validators=[DataRequired('请填写大于0并且小于库存量的购买数量')])

    def validate_product_id(self, field):
        pid = field.data
        g.product = Product.query.filter_by(id=pid, valid=1).first()
        if not g.product:
            abort(404)

    def validate_count(self, field):
        count = int(field.data)
        # product = Product.query.filter_by(id=self.product_id.data).first()
        reserve = g.product.reserve
        if not 1 <= count <= reserve:
            raise ValidationError('购买数量异常')


class OrderPayForm(Form):
    order_id = StringField(validators=[DataRequired()])

    def validate_order_id(self, field):
        oid = field.data
        g.order = Order.query.filter_by(id=oid, status=OrderStatus.WAIT_PAY.value).first()
        if not g.order or g.order.user_id != current_user.id:
            abort(404)


class OrderSendPackageForm(Form):
    package_code = StringField(validators=[DataRequired()])
    order_id = StringField(validators=[DataRequired()])

    def validate_order_id(self, field):
        oid = field.data
        g.order = Order.query.filter_by(id=oid, status=OrderStatus.WAIT_SEND.value).first()
        if not g.order:
            abort(404)
